package com.project.smarthome.main.presenter;

import com.project.smarthome.SmartApplication;
import com.project.smarthome.base.BasePresenter;
import com.project.smarthome.main.MainContract;
import com.project.smarthome.main.model.UserBasicInfo;
import com.sds.smarthome.business.domain.UserService;
import com.sds.smarthome.business.domain.entity.UserInfo;
import com.sds.smarthome.business.domain.service.DomainFactory;
import com.sds.smarthome.business.domain.service.DomainService;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


public class MainPresenter extends BasePresenter implements MainContract.Presenter {

    private MainContract.View mMainView;
    private final DomainService mDomainservice;
    private final UserService mUserservice;

    public MainPresenter(MainContract.View mainView) {
        this.mMainView = mainView;
        mDomainservice = DomainFactory.getDomainService();
        mUserservice = DomainFactory.getUserService();
    }

    @Override
    public void init() {
        mDomainservice.initLocationSevice(SmartApplication.getContext());
        UserInfo userInfo = mDomainservice.loadUserInfo();

        UserBasicInfo basicInfo = new UserBasicInfo();
        if (userInfo != null) {
            basicInfo.setNickName(userInfo.getNickName());
            basicInfo.setSex(userInfo.getSex());
            basicInfo.setBirthDay(userInfo.getBirthday());
            basicInfo.setPhoneNum(userInfo.getPhoneNum());
            basicInfo.setAvatarUrl(userInfo.getProfileImageUrl());
        }
        mMainView.updateProfile(basicInfo);
    }


    @Override
    public void logout() {
        Observable observable = Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                boolean logout = mUserservice.toLogout();
                e.onNext(logout);
            }

        });
        Disposable subscription = observable.
                subscribeOn(getJobExecutor()).
                observeOn(getUiExecutor()).
                subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean logout) throws Exception {
                        if (logout) {
                            mDomainservice.clearCache();
//                            ViewNavigator.navFromMainToLogin();
                            mMainView.exit();
                        } else {
                            mMainView.showToast("logout error");
                        }
                    }

                });
        addSubscription(subscription);
    }

    @Override
    public void destroy() {
        super.destroy();
        mDomainservice.destorySmartDevice();
        mMainView = null;
    }

}
